package com.jgp.third.wx.controller;

import com.jgp.sys.controller.JGPFrontController;
import com.jgp.sys.ui.Result;
import com.jgp.third.wx.JGPWxUtil;
import com.jgp.third.wx.model.WxUseFor;
import com.jgp.third.wx.model.WxUserInfo;
import com.jgp.third.wx.service.WxService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2018/6/2
 */
@CrossOrigin
@Controller
@RequestMapping("third/wx/wxInterfaceController")
public class WxInterfaceController extends JGPFrontController {

    private Logger logger = LoggerFactory.getLogger(WxInterfaceController.class);

    @Autowired
    private WxService wxService;
    
    @RequestMapping(value = "/checkToken")
    @ResponseBody
    public String doService(HttpServletRequest request, @RequestBody(required = false) String body, Model
            model) {
        logger.info("微信通知：" + request.getQueryString());
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        // 加密/校验流程：
        // 1. 将token、timestamp、nonce三个参数进行字典序排序
        // 2. 将三个参数字符串拼接成一个字符串进行sha1加密
        // 3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        String token = "activity";
        String[] arrStr = {token, timestamp, nonce};
        Arrays.sort(arrStr);
        StringBuilder signBuilder = new StringBuilder().append(arrStr[0]).append(arrStr[1]).append(arrStr[2]);
        if (DigestUtils.sha1Hex(signBuilder.toString()).equals(signature)) {
            if (StringUtils.isNotBlank(body)) {

            }
        }
        return echostr;
    }

    @RequestMapping("/shareConfig")
    @ResponseBody
    public Result shareConfig(Long useForId) {
        WxUseFor useFor = wxService.queryUseForById(useForId);
        Map<String,Object> map = new HashMap<>();
        map.put("title",useFor.getShareTitle());
        map.put("link",useFor.getShareLink());
        map.put("image",useFor.getShareImage());
        map.put("desc",useFor.getShareDesc());
        map.put("type",useFor.getShareType());
        map.put("dataUrl",useFor.getShareDataUrl());
        return new Result(true).addData("shareConfig", map);
    }

    @RequestMapping("/jsConfig")
    @ResponseBody
    public Result jsConfig(String url, String useForId) {
        return new Result(true).addData("jsConfig", JGPWxUtil.jsConfig(url, useForId));
    }


    @RequestMapping("/toAuth")
    public String toAuth(HttpServletRequest request) {
        String useForId = request.getParameter("useForId");
        String domain = request.getParameter("domain");
        String bizId = request.getParameter("bizId");
        String authBack = request.getScheme() + "://" + domain + request.getContextPath() +
                "/third/wx/wxInterfaceController/authBack";
        String appId = wxService.queryConfigByForId(Long.valueOf(useForId)).getAppId();
        String authUrl = JGPWxUtil.getAuthRedirectUrl(appId, authBack, JGPWxUtil.AUTH_NO_STATIC, useForId,bizId);
        return "redirect:" + authUrl;
    }


    @RequestMapping("/authBack")
    public String authBack(HttpServletRequest request) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String[] params = state.split(",");
        String useForId = params[0];
        String bizId = params[1];
        WxUseFor useFor = wxService.queryUseForById(Long.valueOf(useForId));
        WxUserInfo user = JGPWxUtil.getUserInfoFromWxServer(code, useForId);
        String authBack = request.getScheme() + "://" + useFor.getDomain() + request.getContextPath() +
                useFor.getPath();
        authBack += "?openId=" + user.getOpenId() + "&useForId=" + useForId+"&bizId="+bizId;
        return "redirect:" + authBack;
    }
}
